using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Agricultural_Sales.CS; // 添加这行引用Upload_Image类
using System.Data.SqlClient;
using System.Configuration;

namespace Agricultural_Sales.ASP
{
    public partial class Admin : System.Web.UI.Page
    {
        // 页面加载事件，初始化页面状态和默认视图
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // 检查用户是否已登录
                if (Session["UserId"] == null || Session["UserType"] == null || Session["UserType"].ToString() != "管理员")
                {
                    Response.Redirect("~/ASP/Login.aspx");
                    return;
                }

                // 加载管理员头像
                LoadAdminAvatar();

                // 设置默认视图为管理员管理
                ContentMultiView.ActiveViewIndex = 0;
                navigationmenu.Items[0].Selected = true; // 修改为小写

                // 加载统计数据
                LoadStatistics();
            }
        }

        // 加载管理员头像的方法
        private void LoadAdminAvatar()
        {
            try
            {
                if (Session["UserId"] != null)
                {
                    string userId = Session["UserId"].ToString();
                    string connectionString = ConfigurationManager.ConnectionStrings["AgriculturalSalesConnectionString"].ConnectionString;

                    using (SqlConnection conn = new SqlConnection(connectionString))
                    {
                        conn.Open();
                        string query = "SELECT UserImagee FROM Users WHERE UserId = @UserId AND UserType = '管理员'";
                        using (SqlCommand cmd = new SqlCommand(query, conn))
                        {
                            cmd.Parameters.AddWithValue("@UserId", userId);
                            object result = cmd.ExecuteScalar();

                            if (result != null && !string.IsNullOrEmpty(result.ToString()))
                            {
                                string imagePath = result.ToString();
                                // 检查路径是否已经包含~/，如果包含则直接使用，否则添加~/Image/前缀
                                if (imagePath.StartsWith("~/"))
                                {
                                    imgAdminAvatar.ImageUrl = imagePath;
                                }
                                else
                                {
                                    imgAdminAvatar.ImageUrl = "~/Image/" + imagePath;
                                }
                            }
                            else
                            {
                                // 如果没有头像，显示默认管理员头像
                                imgAdminAvatar.ImageUrl = "~/Image/admin1.jpg";
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // 出错时显示默认头像
                imgAdminAvatar.ImageUrl = "~/Image/admin1.jpg";
                // 可以记录错误日志
                System.Diagnostics.Debug.WriteLine("加载管理员头像失败: " + ex.Message);
            }
        }

        // 菜单项点击事件处理，用于切换不同的管理视图
        // 根据用户点击的菜单项来显示对应的管理界面（管理员管理、用户管理、分类管理、商品管理）
        protected void Navigationmenu_MenuItemClick(object sender, MenuEventArgs e)
        {
            // 根据选中的菜单项切换MultiView的视图
            int viewIndex = Convert.ToInt32(e.Item.Value);
            ContentMultiView.ActiveViewIndex = viewIndex;

            // 清除所有菜单项的选中状态
            foreach (MenuItem item in navigationmenu.Items) // 修改为小写
            {
                item.Selected = false;
            }

            // 设置当前菜单项为选中状态
            e.Item.Selected = true;
        }

        // 搜索按钮点击事件，根据管理员编号和名字进行查询
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            string searchUserId = txtSearchUserId.Text.Trim();
            string searchUserName = txtSearchUserName.Text.Trim();

            // 构建动态查询条件
            string whereClause = "[UserType] = '管理员'";

            if (!string.IsNullOrEmpty(searchUserId))
            {
                whereClause += " AND [UserId] = " + searchUserId;
            }

            if (!string.IsNullOrEmpty(searchUserName))
            {
                whereClause += " AND [UserName] LIKE '%" + searchUserName.Replace("'", "''") + "%'";
            }

            // 更新SqlDataSource的查询命令
            SqlDataSource1.SelectCommand = "SELECT * FROM [Users] WHERE " + whereClause;

            // 重新绑定数据
            GridView1.DataBind();
        }

        // 重置按钮点击事件，清空搜索条件并显示所有管理员信息
        protected void btnReset_Click(object sender, EventArgs e)
        {
            // 清空搜索文本框
            txtSearchUserId.Text = "";
            txtSearchUserName.Text = "";

            // 恢复原始查询命令
            SqlDataSource1.SelectCommand = "SELECT * FROM [Users] WHERE [UserType] = '管理员'";

            // 重新绑定数据
            GridView1.DataBind();
        }

        // 退出登录事件处理，清除用户会话并重定向到首页
        // 当管理员点击退出登录时，清理所有会话数据并跳转到登录页面
        protected void lnkLogout_Click(object sender, EventArgs e)
        {
            // 清除会话
            Session.Clear();
            Session.Abandon();

            // 重定向到登录页面
            Response.Redirect("~/ASP/Login.aspx");
        }

        // GridView行更新完成事件，处理数据更新后的反馈
        // 在管理员信息更新完成后，向用户显示操作结果（成功或失败）
        protected void GridView1_RowUpdated(object sender, GridViewUpdatedEventArgs e)
        {
            if (e.Exception == null)
            {
                // 更新成功，可以添加成功提示
                Response.Write("<script>alert('更新成功!');</script>");
            }
            else
            {
                // 更新失败，显示错误信息
                Response.Write($"<script>alert('更新失败: {e.Exception.Message}');</script>");
                e.ExceptionHandled = true;
            }
        }

        // GridView行更新前事件，处理图片上传和数据验证
        // 在更新管理员信息之前，处理头像图片的上传，如果没有上传新图片则保持原图片
        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            //执行更新前，上传图片
            Upload_Image c1 = new Upload_Image();
            FileUpload ff = (FileUpload)GridView1.Rows[e.RowIndex].Cells[4].FindControl("FileUpload1");
            if (ff.HasFile)//如果上传图片，就修改图片
            {
                Session["p"] = c1.uploadimg(ff);
                // 将新的图片路径设置到更新参数中
                e.NewValues["UserImagee"] = Session["p"];
                Response.Write("<script>alert('上传图片成功！');</script>");//提示上传图片成功
            }
            else
            {
                HiddenField hh = (HiddenField)GridView1.Rows[e.RowIndex].Cells[4].FindControl("HiddenField1");
                Session["p"] = hh.Value;
                // 保持原有图片路径
                e.NewValues["UserImagee"] = hh.Value;
                Response.Write("<script>alert('没有上传图片，使用原图片！');</script>");//提示没有上传图片
            }
        }

        // 添加用户按钮点击事件，处理新管理员的添加操作
        // 验证用户输入的完整性，处理头像上传，然后将新管理员信息插入数据库
        protected void btnAddUser_Click(object sender, EventArgs e)
        {
            try
            {
                // 验证输入
                if (string.IsNullOrWhiteSpace(txtUserName.Text) ||
                    string.IsNullOrWhiteSpace(txtPassword.Text) ||
                    string.IsNullOrWhiteSpace(txtPhone.Text))
                {
                    Response.Write("<script>alert('请填写完整的用户信息！');</script>");
                    return;
                }

                // 处理图片上传
                string imagePath = "~/Image/admin1.jpg"; // 默认头像
                if (fuUserImage.HasFile)
                {
                    Upload_Image uploadHelper = new Upload_Image();
                    imagePath = uploadHelper.uploadimg(fuUserImage);
                }

                // 使用SqlDataSource插入数据
                SqlDataSource1.InsertParameters["UserName"].DefaultValue = txtUserName.Text.Trim();
                SqlDataSource1.InsertParameters["Password"].DefaultValue = txtPassword.Text.Trim();
                SqlDataSource1.InsertParameters["Phone"].DefaultValue = txtPhone.Text.Trim();
                SqlDataSource1.InsertParameters["UserImagee"].DefaultValue = imagePath;
                SqlDataSource1.InsertParameters["Address"].DefaultValue = txtAddress.Text.Trim();
                SqlDataSource1.InsertParameters["UserType"].DefaultValue = "管理员";

                // 执行插入
                SqlDataSource1.Insert();

                // 刷新GridView
                GridView1.DataBind();

                // 清空表单并关闭模态框
                txtUserName.Text = "";
                txtPassword.Text = "";
                txtPhone.Text = "";
                txtAddress.Text = "";

                Response.Write("<script>alert('管理员添加成功！'); hideAddUserModal();</script>");
            }
            catch (Exception ex)
            {
                Response.Write($"<script>alert('添加失败：{ex.Message}');</script>");
            }
        }

        // GridView行删除事件，在删除管理员前进行验证
        // 可以在此处添加删除前的业务逻辑验证，比如检查是否为最后一个管理员
        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                // 可以在这里添加删除前的验证逻辑
                // 例如：检查是否为最后一个管理员等
            }
            catch (Exception ex)
            {
                Response.Write($"<script>alert('删除失败：{ex.Message}');</script>");
                e.Cancel = true;
            }
        }

        // GridView行删除完成事件，处理删除操作的结果反馈
        // 在管理员删除完成后，向用户显示操作结果
        protected void GridView1_RowDeleted(object sender, GridViewDeletedEventArgs e)
        {
            if (e.Exception == null)
            {
                Response.Write("<script>alert('删除成功!');</script>");
            }
            else
            {
                Response.Write($"<script>alert('删除失败: {e.Exception.Message}');</script>");
                e.ExceptionHandled = true;
            }
        }

        /// <summary>
        /// 产品管理相关事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void GridViewProducts_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            // 产品更新时的图片处理
            Upload_Image uploadHelper = new Upload_Image();
            FileUpload productImageUpload = (FileUpload)((GridView)sender).Rows[e.RowIndex].FindControl("FileUploadProductImage");

            if (productImageUpload != null && productImageUpload.HasFile)
            {
                string imagePath = uploadHelper.uploadimg(productImageUpload);
                e.NewValues["ImageUrl"] = imagePath;
                Response.Write("<script>alert('产品图片上传成功！');</script>");
            }
        }

        protected void GridViewProducts_RowUpdated(object sender, GridViewUpdatedEventArgs e)
        {
            if (e.Exception == null)
            {
                Response.Write("<script>alert('产品更新成功!');</script>");
            }
            else
            {
                Response.Write($"<script>alert('产品更新失败: {e.Exception.Message}');</script>");
                e.ExceptionHandled = true;
            }
        }

        protected void GridViewProducts_RowDeleted(object sender, GridViewDeletedEventArgs e)
        {
            if (e.Exception == null)
            {
                Response.Write("<script>alert('产品删除成功!');</script>");
            }
            else
            {
                Response.Write($"<script>alert('产品删除失败: {e.Exception.Message}');</script>");
                e.ExceptionHandled = true;
            }
        }

        /// <summary>
        /// 订单管理相关事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void GridViewOrders_RowUpdated(object sender, GridViewUpdatedEventArgs e)
        {
            if (e.Exception == null)
            {
                Response.Write("<script>alert('订单状态更新成功!');</script>");
            }
            else
            {
                Response.Write($"<script>alert('订单更新失败: {e.Exception.Message}');</script>");
                e.ExceptionHandled = true;
            }
        }

        /// <summary>
        /// 分类管理相关事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void GridViewCategories_RowUpdated(object sender, GridViewUpdatedEventArgs e)
        {
            if (e.Exception == null)
            {
                Response.Write("<script>alert('分类更新成功!');</script>");
            }
            else
            {
                Response.Write($"<script>alert('分类更新失败: {e.Exception.Message}');</script>");
                e.ExceptionHandled = true;
            }
        }

        protected void GridViewCategories_RowDeleted(object sender, GridViewDeletedEventArgs e)
        {
            if (e.Exception == null)
            {
                Response.Write("<script>alert('分类删除成功!');</script>");
            }
            else
            {
                Response.Write($"<script>alert('分类删除失败: {e.Exception.Message}');</script>");
                e.ExceptionHandled = true;
            }
        }

        // 用户搜索按钮点击事件，根据选择的搜索类型和内容进行查询
        protected void btnSearchNormalUser_Click(object sender, EventArgs e)
        {
            string searchType = ddlSearchType.SelectedValue;
            string searchContent = txtSearchContent.Text.Trim();

            // 构建动态查询条件
            string whereClause = "[UserType] = '普通用户'";

            if (!string.IsNullOrEmpty(searchContent))
            {
                switch (searchType)
                {
                    case "UserId":
                        // 验证是否为数字
                        if (int.TryParse(searchContent, out int userId))
                        {
                            whereClause += " AND [UserId] = " + userId;
                        }
                        else
                        {
                            Response.Write("<script>alert('用户编号必须是数字！');</script>");
                            return;
                        }
                        break;
                    case "UserName":
                        whereClause += " AND [UserName] LIKE '%" + searchContent.Replace("'", "''") + "%'";
                        break;
                    case "Address":
                        whereClause += " AND [Address] LIKE '%" + searchContent.Replace("'", "''") + "%'";
                        break;
                }
            }

            // 更新SqlDataSource的查询命令
            SqlDataSource2.SelectCommand = "SELECT * FROM [Users] WHERE " + whereClause;

            // 重新绑定数据
            GridView2.DataBind();
        }

        // 用户重置按钮点击事件，清空搜索条件并显示所有普通用户信息
        protected void btnResetNormalUser_Click(object sender, EventArgs e)
        {
            // 清空搜索内容
            txtSearchContent.Text = "";
            ddlSearchType.SelectedIndex = 0; // 选择第一项

            // 恢复原始查询命令
            SqlDataSource2.SelectCommand = "SELECT * FROM [Users] WHERE [UserType] = '普通用户'";

            // 重新绑定数据
            GridView2.DataBind();
        }

        // GridView2行更新完成事件，处理用户数据更新后的反馈
        protected void GridView2_RowUpdated(object sender, GridViewUpdatedEventArgs e)
        {
            if (e.Exception == null)
            {
                Response.Write("<script>alert('用户信息更新成功!');</script>");
            }
            else
            {
                Response.Write($"<script>alert('更新失败: {e.Exception.Message}');</script>");
                e.ExceptionHandled = true;
            }
        }

        // GridView2行更新前事件，处理用户头像上传和数据验证
        protected void GridView2_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            // 执行更新前，上传图片
            Upload_Image c1 = new Upload_Image();
            FileUpload ff = (FileUpload)GridView2.Rows[e.RowIndex].Cells[4].FindControl("FileUpload2");
            if (ff.HasFile) // 如果上传图片，就修改图片
            {
                Session["p2"] = c1.uploadimg(ff);
                // 将新的图片路径设置到更新参数中
                e.NewValues["UserImagee"] = Session["p2"];
                Response.Write("<script>alert('上传图片成功！');</script>"); // 提示上传图片成功
            }
            else
            {
                HiddenField hh = (HiddenField)GridView2.Rows[e.RowIndex].Cells[4].FindControl("HiddenField2");
                Session["p2"] = hh.Value;
                // 保持原有图片路径
                e.NewValues["UserImagee"] = hh.Value;
                Response.Write("<script>alert('没有上传图片，使用原图片！');</script>"); // 提示没有上传图片
            }
        }

        // 添加普通用户按钮点击事件，处理新用户的添加操作
        protected void btnAddNormalUser_Click(object sender, EventArgs e)
        {
            try
            {
                // 验证必填字段
                if (string.IsNullOrWhiteSpace(txtNormalUserName.Text) ||
                    string.IsNullOrWhiteSpace(txtNormalPassword.Text))
                {
                    Response.Write("<script>alert('用户名和密码不能为空！');</script>");
                    return;
                }

                // 处理头像上传
                string imagePath = "~/Image/user1.jpg"; // 默认头像
                if (fuNormalUserImage.HasFile)
                {
                    Upload_Image uploadHelper = new Upload_Image();
                    imagePath = uploadHelper.uploadimg(fuNormalUserImage);
                }

                // 使用SqlDataSource插入数据
                SqlDataSource2.InsertParameters["UserName"].DefaultValue = txtNormalUserName.Text.Trim();
                SqlDataSource2.InsertParameters["Password"].DefaultValue = txtNormalPassword.Text.Trim();
                SqlDataSource2.InsertParameters["Phone"].DefaultValue = txtNormalPhone.Text.Trim();
                SqlDataSource2.InsertParameters["UserImagee"].DefaultValue = imagePath;
                SqlDataSource2.InsertParameters["Address"].DefaultValue = txtNormalAddress.Text.Trim();
                SqlDataSource2.InsertParameters["UserType"].DefaultValue = "普通用户";

                // 执行插入
                SqlDataSource2.Insert();

                // 刷新GridView
                GridView2.DataBind();

                // 清空表单并关闭模态框
                txtNormalUserName.Text = "";
                txtNormalPassword.Text = "";
                txtNormalPhone.Text = "";
                txtNormalAddress.Text = "";

                Response.Write("<script>alert('用户添加成功！'); hideAddNormalUserModal();</script>");
            }
            catch (Exception ex)
            {
                Response.Write($"<script>alert('添加失败：{ex.Message}');</script>");
            }
        }

        // GridView2行删除事件，在删除用户前进行验证
        protected void GridView2_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                // 获取要删除的用户ID
                int userId = Convert.ToInt32(GridView2.DataKeys[e.RowIndex].Value);

                // 可以在这里添加删除前的验证逻辑
                // 例如：检查用户是否有关联的订单等
                // string checkOrderSql = "SELECT COUNT(*) FROM [Orders] WHERE [UserId] = " + userId;

                // 如果有关联数据，可以阻止删除
                // e.Cancel = true;
                // Response.Write("<script>alert('该用户有关联订单，无法删除！');</script>");
            }
            catch (Exception ex)
            {
                Response.Write($"<script>alert('删除失败：{ex.Message}');</script>");
                e.Cancel = true;
            }
        }

        // GridView2行删除完成事件，处理删除操作的结果反馈
        protected void GridView2_RowDeleted(object sender, GridViewDeletedEventArgs e)
        {
            if (e.Exception == null)
            {
                Response.Write("<script>alert('用户删除成功!');</script>");
            }
            else
            {
                Response.Write($"<script>alert('删除失败: {e.Exception.Message}');</script>");
                e.ExceptionHandled = true;
            }
        }

        // 分类搜索按钮点击事件，根据分类编号和名称进行查询
        protected void btnSearchCategory_Click(object sender, EventArgs e)
        {
            try
            {
                string searchType = ddlCategorySearchType.SelectedValue;
                string searchContent = txtCategorySearchContent.Text.Trim();

                // 构建动态查询条件
                string whereClause = "1=1"; // 默认条件

                if (!string.IsNullOrEmpty(searchContent))
                {
                    switch (searchType)
                    {
                        case "CategoryId":
                            if (int.TryParse(searchContent, out int categoryId))
                            {
                                whereClause = "[CategoryId] = " + categoryId;
                            }
                            else
                            {
                                Response.Write("<script>alert('分类编号必须是数字！');</script>");
                                return;
                            }
                            break;
                        case "CategoryName":
                            whereClause = "[CategoryName] LIKE '%" + searchContent.Replace("'", "''") + "%'";
                            break;
                    }
                }

                // 更新SqlDataSource的查询命令
                SqlDataSource3.SelectCommand = "SELECT * FROM [ProductCategory] WHERE " + whereClause;

                // 重新绑定数据
                GridView3.DataBind();
            }
            catch (Exception ex)
            {
                Response.Write($"<script>alert('搜索失败：{ex.Message}');</script>");
            }
        }

        // 分类重置按钮点击事件，清空搜索条件并显示所有分类信息
        protected void btnResetCategory_Click(object sender, EventArgs e)
        {
            try
            {
                // 清空搜索控件
                ddlCategorySearchType.SelectedIndex = 0;
                txtCategorySearchContent.Text = "";

                // 恢复原始查询命令
                SqlDataSource3.SelectCommand = "SELECT * FROM [ProductCategory]";

                // 重新绑定数据
                GridView3.DataBind();
            }
            catch (Exception ex)
            {
                Response.Write($"<script>alert('重置失败：{ex.Message}');</script>");
            }
        }

        // 添加分类按钮点击事件，处理新分类的添加操作
        protected void btnAddCategory_Click(object sender, EventArgs e)
        {
            try
            {
                // 验证必填字段
                if (string.IsNullOrWhiteSpace(txtCategoryName.Text))
                {
                    Response.Write("<script>alert('分类名称不能为空！');</script>");
                    return;
                }

                // 检查分类名称是否已存在
                string checkSql = "SELECT COUNT(*) FROM [ProductCategory] WHERE [CategoryName] = '" + txtCategoryName.Text.Trim().Replace("'", "''") + "'";
                // 这里可以添加重复检查逻辑

                // 使用SqlDataSource插入数据
                SqlDataSource3.InsertParameters["CategoryName"].DefaultValue = txtCategoryName.Text.Trim();

                // 执行插入
                SqlDataSource3.Insert();

                // 刷新GridView
                GridView3.DataBind();

                // 清空表单并关闭模态框
                txtCategoryName.Text = "";

                Response.Write("<script>alert('分类添加成功！'); hideAddCategoryModal();</script>");
            }
            catch (Exception ex)
            {
                Response.Write($"<script>alert('添加失败：{ex.Message}');</script>");
            }
        }

        // GridView3行更新事件，处理分类信息的更新
        protected void GridView3_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                // 获取新的分类名称
                string newCategoryName = e.NewValues["CategoryName"].ToString().Trim();

                // 验证分类名称不能为空
                if (string.IsNullOrWhiteSpace(newCategoryName))
                {
                    Response.Write("<script>alert('分类名称不能为空！');</script>");
                    e.Cancel = true;
                    return;
                }

                // 可以在这里添加重复检查逻辑
                int categoryId = Convert.ToInt32(GridView3.DataKeys[e.RowIndex].Value);
                // string checkSql = "SELECT COUNT(*) FROM [ProductCategory] WHERE [CategoryName] = '" + newCategoryName.Replace("'", "''") + "' AND [CategoryId] != " + categoryId;
            }
            catch (Exception ex)
            {
                Response.Write($"<script>alert('更新失败：{ex.Message}');</script>");
                e.Cancel = true;
            }
        }

        // GridView3行更新完成事件，处理更新操作的结果反馈
        protected void GridView3_RowUpdated(object sender, GridViewUpdatedEventArgs e)
        {
            if (e.Exception == null)
            {
                Response.Write("<script>alert('分类更新成功!');</script>");
            }
            else
            {
                Response.Write($"<script>alert('更新失败: {e.Exception.Message}');</script>");
                e.ExceptionHandled = true;
            }
        }

        // GridView3行删除事件，在删除分类前进行验证
        protected void GridView3_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                // 获取要删除的分类ID
                int categoryId = Convert.ToInt32(GridView3.DataKeys[e.RowIndex].Value);

                // 检查该分类下是否有商品
                // string checkProductSql = "SELECT COUNT(*) FROM [Product] WHERE [CategoryId] = " + categoryId;
                // 如果有关联商品，可以阻止删除或提示用户
                // e.Cancel = true;
                // Response.Write("<script>alert('该分类下还有商品，无法删除！请先删除或转移相关商品。');</script>");
            }
            catch (Exception ex)
            {
                Response.Write($"<script>alert('删除失败：{ex.Message}');</script>");
                e.Cancel = true;
            }
        }

        // GridView3行删除完成事件，处理删除操作的结果反馈
        protected void GridView3_RowDeleted(object sender, GridViewDeletedEventArgs e)
        {
            if (e.Exception == null)
            {
                Response.Write("<script>alert('分类删除成功!');</script>");
            }
            else
            {
                Response.Write($"<script>alert('删除失败: {e.Exception.Message}');</script>");
                e.ExceptionHandled = true;
            }
        }
        // 商品搜索按钮点击事件
        protected void btnSearchProduct_Click(object sender, EventArgs e)
        {
            try
            {
                string searchType = ddlProductSearchType.SelectedValue;
                string searchContent = txtProductSearchContent.Text.Trim();

                // 构建动态查询条件
                string whereClause = "1=1"; // 默认条件

                if (!string.IsNullOrEmpty(searchContent))
                {
                    switch (searchType)
                    {
                        case "ProductId":
                            if (int.TryParse(searchContent, out int productId))
                            {
                                whereClause = "[ProductId] = " + productId;
                            }
                            else
                            {
                                Response.Write("<script>alert('商品编号必须是数字！');</script>");
                                return;
                            }
                            break;
                        case "Name":
                            whereClause = "[Name] LIKE '%" + searchContent.Replace("'", "''") + "%'";
                            break;
                        case "CategoryId":
                            if (int.TryParse(searchContent, out int categoryId))
                            {
                                whereClause = "[CategoryId] = " + categoryId;
                            }
                            else
                            {
                                Response.Write("<script>alert('分类编号必须是数字！');</script>");
                                return;
                            }
                            break;
                        case "Origin":
                            whereClause = "[Origin] LIKE '%" + searchContent.Replace("'", "''") + "%'";
                            break;
                        case "UserId":
                            if (int.TryParse(searchContent, out int userId))
                            {
                                whereClause = "[UserId] = " + userId;
                            }
                            else
                            {
                                Response.Write("<script>alert('管理员编号必须是数字！');</script>");
                                return;
                            }
                            break;
                    }
                }

                // 更新SqlDataSource的查询命令
                SqlDataSource4.SelectCommand = "SELECT * FROM [Product] WHERE " + whereClause;

                // 重新绑定数据
                GridView4.DataBind();
            }
            catch (Exception ex)
            {
                Response.Write($"<script>alert('搜索失败：{ex.Message}');</script>");
            }
        }

        // 商品重置按钮点击事件
        protected void btnResetProduct_Click(object sender, EventArgs e)
        {
            try
            {
                // 清空搜索控件
                ddlProductSearchType.SelectedIndex = 0;
                txtProductSearchContent.Text = "";

                // 恢复原始查询命令
                SqlDataSource4.SelectCommand = "SELECT * FROM [Product]";

                // 重新绑定数据
                GridView4.DataBind();
            }
            catch (Exception ex)
            {
                Response.Write($"<script>alert('重置失败：{ex.Message}');</script>");
            }
        }

        // 添加商品按钮点击事件
        protected void btnAddProduct_Click(object sender, EventArgs e)
        {
            try
            {
                // 验证必填字段
                if (string.IsNullOrWhiteSpace(txtProductName.Text) ||
                    string.IsNullOrWhiteSpace(txtProductPrice.Text) ||
                    string.IsNullOrWhiteSpace(txtProductInventory.Text))
                {
                    Response.Write("<script>alert('商品名称、价格和库存数量不能为空！');</script>");
                    return;
                }

                // 验证价格和库存格式
                if (!decimal.TryParse(txtProductPrice.Text, out decimal price) || price <= 0)
                {
                    Response.Write("<script>alert('请输入有效的价格！');</script>");
                    return;
                }

                if (!int.TryParse(txtProductInventory.Text, out int inventory) || inventory < 0)
                {
                    Response.Write("<script>alert('请输入有效的库存数量！');</script>");
                    return;
                }

                // 处理图片上传
                string imagePath = "~/Image/product_default.jpg"; // 默认商品图片
                if (fuProductImage.HasFile)
                {
                    Upload_Image uploadHelper = new Upload_Image();
                    imagePath = uploadHelper.uploadimg(fuProductImage);
                }

                // 获取当前管理员ID（从Session或其他方式获取）
                int currentUserId = 5301; // 这里应该从Session中获取当前登录的管理员ID
                if (Session["UserId"] != null)
                {
                    currentUserId = Convert.ToInt32(Session["UserId"]);
                }

                // 使用SqlDataSource插入数据
                SqlDataSource4.InsertParameters["CategoryId"].DefaultValue = ddlProductCategory.SelectedValue;
                SqlDataSource4.InsertParameters["UserId"].DefaultValue = currentUserId.ToString();
                SqlDataSource4.InsertParameters["Name"].DefaultValue = txtProductName.Text.Trim();
                SqlDataSource4.InsertParameters["Origin"].DefaultValue = txtProductOrigin.Text.Trim();
                SqlDataSource4.InsertParameters["Price"].DefaultValue = price.ToString();
                SqlDataSource4.InsertParameters["Inventory"].DefaultValue = inventory.ToString();
                SqlDataSource4.InsertParameters["Unit"].DefaultValue = txtProductUnit.Text.Trim();
                SqlDataSource4.InsertParameters["Descr"].DefaultValue = txtProductDescr.Text.Trim();
                SqlDataSource4.InsertParameters["ImageUrl"].DefaultValue = imagePath;

                // 执行插入
                SqlDataSource4.Insert();

                // 刷新GridView
                GridView4.DataBind();

                // 清空表单并关闭模态框
                txtProductName.Text = "";
                txtProductOrigin.Text = "";
                txtProductPrice.Text = "";
                txtProductInventory.Text = "";
                txtProductUnit.Text = "";
                txtProductDescr.Text = "";
                ddlProductCategory.SelectedIndex = 0;

                Response.Write("<script>alert('商品添加成功！'); hideAddProductModal();</script>");
            }
            catch (Exception ex)
            {
                Response.Write($"<script>alert('添加失败：{ex.Message}');</script>");
            }
        }

        // GridView4行更新前事件，处理商品图片上传
        protected void GridView4_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                // 执行更新前，上传图片
                Upload_Image c1 = new Upload_Image();
                FileUpload ff = (FileUpload)GridView4.Rows[e.RowIndex].FindControl("FileUpload4");
                if (ff.HasFile) // 如果上传图片，就修改图片
                {
                    Session["p4"] = c1.uploadimg(ff);
                    // 将新的图片路径设置到更新参数中
                    e.NewValues["ImageUrl"] = Session["p4"];
                    Response.Write("<script>alert('上传图片成功！');</script>"); // 提示上传图片成功
                }
                else
                {
                    HiddenField hh = (HiddenField)GridView4.Rows[e.RowIndex].FindControl("HiddenField4");
                    Session["p4"] = hh.Value;
                    // 保持原有图片路径
                    e.NewValues["ImageUrl"] = hh.Value;
                    Response.Write("<script>alert('没有上传图片，使用原图片！');</script>"); // 提示没有上传图片
                }

                // 验证必填字段
                if (string.IsNullOrWhiteSpace(e.NewValues["Name"].ToString()) ||
                    string.IsNullOrWhiteSpace(e.NewValues["Price"].ToString()) ||
                    string.IsNullOrWhiteSpace(e.NewValues["Inventory"].ToString()))
                {
                    Response.Write("<script>alert('商品名称、价格和库存数量不能为空！');</script>");
                    e.Cancel = true;
                    return;
                }

                // 验证价格和库存格式
                if (!decimal.TryParse(e.NewValues["Price"].ToString(), out decimal price) || price <= 0)
                {
                    Response.Write("<script>alert('请输入有效的价格！');</script>");
                    e.Cancel = true;
                    return;
                }

                if (!int.TryParse(e.NewValues["Inventory"].ToString(), out int inventory) || inventory < 0)
                {
                    Response.Write("<script>alert('请输入有效的库存数量！');</script>");
                    e.Cancel = true;
                    return;
                }
            }
            catch (Exception ex)
            {
                Response.Write($"<script>alert('更新失败：{ex.Message}');</script>");
                e.Cancel = true;
            }
        }

        // GridView4行更新完成事件
        protected void GridView4_RowUpdated(object sender, GridViewUpdatedEventArgs e)
        {
            if (e.Exception == null)
            {
                Response.Write("<script>alert('商品信息更新成功!');</script>");
            }
            else
            {
                Response.Write($"<script>alert('更新失败: {e.Exception.Message}');</script>");
                e.ExceptionHandled = true;
            }
        }

        // GridView4行删除事件，在删除商品前进行验证
        protected void GridView4_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                // 获取要删除的商品ID
                int productId = Convert.ToInt32(GridView4.DataKeys[e.RowIndex].Value);

                // 可以在这里添加删除前的验证逻辑
                // 例如：检查商品是否有关联的订单等
                // string checkOrderSql = "SELECT COUNT(*) FROM [OrderProduct] WHERE [ProductId] = " + productId;
                // 如果有关联数据，可以阻止删除
                // e.Cancel = true;
                // Response.Write("<script>alert('该商品有关联订单，无法删除！');</script>");
            }
            catch (Exception ex)
            {
                Response.Write($"<script>alert('删除失败：{ex.Message}');</script>");
                e.Cancel = true;
            }
        }

        // GridView4行删除完成事件
        protected void GridView4_RowDeleted(object sender, GridViewDeletedEventArgs e)
        {
            if (e.Exception == null)
            {
                Response.Write("<script>alert('商品删除成功!');</script>");
            }
            else
            {
                Response.Write($"<script>alert('删除失败: {e.Exception.Message}');</script>");
                e.ExceptionHandled = true;
            }
        }
        // 订单搜索按钮点击事件
        protected void btnSearchOrder_Click(object sender, EventArgs e)
        {
            string searchType = ddlOrderSearchType.SelectedValue;
            string searchContent = txtOrderSearchContent.Text.Trim();

            // 构建动态查询条件
            string whereClause = "1=1";

            if (!string.IsNullOrEmpty(searchContent))
            {
                switch (searchType)
                {
                    case "OrderId":
                        // 验证是否为数字
                        if (int.TryParse(searchContent, out int orderId))
                        {
                            whereClause += " AND [OrderId] = " + orderId;
                        }
                        else
                        {
                            Response.Write("<script>alert('订单编号必须是数字！');</script>");
                            return;
                        }
                        break;
                    case "UserId":
                        // 验证是否为数字
                        if (int.TryParse(searchContent, out int userId))
                        {
                            whereClause += " AND [UserId] = " + userId;
                        }
                        else
                        {
                            Response.Write("<script>alert('用户编号必须是数字！');</script>");
                            return;
                        }
                        break;
                    case "OrderState":
                        whereClause += " AND [OrderState] LIKE '%" + searchContent.Replace("'", "''") + "%'";
                        break;
                    case "ContactPhone":
                        whereClause += " AND [ContactPhone] LIKE '%" + searchContent.Replace("'", "''") + "%'";
                        break;
                }
            }

            // 更新SqlDataSource的查询命令
            SqlDataSource5.SelectCommand = "SELECT * FROM [Order] WHERE " + whereClause;

            // 重新绑定数据
            GridView5.DataBind();
        }

        // 订单重置按钮点击事件
        protected void btnResetOrder_Click(object sender, EventArgs e)
        {
            // 清空搜索内容
            txtOrderSearchContent.Text = "";
            ddlOrderSearchType.SelectedIndex = 0; // 选择第一项

            // 恢复原始查询命令
            SqlDataSource5.SelectCommand = "SELECT * FROM [Order]";

            // 重新绑定数据
            GridView5.DataBind();

            // 清空支付信息显示
            SqlDataSource6.SelectParameters["OrderId"].DefaultValue = "-1";
            FormView1.DataBind();
        }

        // 显示支付信息按钮点击事件
        protected void btnShowPayment_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            string orderId = btn.CommandArgument;

            // 设置SqlDataSource6的参数来显示对应订单的支付信息
            SqlDataSource6.SelectParameters["OrderId"].DefaultValue = orderId;
            FormView1.DataBind();
        }

        // GridView5行更新完成事件
        protected void GridView5_RowUpdated(object sender, GridViewUpdatedEventArgs e)
        {
            if (e.Exception == null)
            {
                Response.Write("<script>alert('订单信息更新成功!');</script>");
            }
            else
            {
                Response.Write($"<script>alert('更新失败: {e.Exception.Message}');</script>");
                e.ExceptionHandled = true;
            }
        }

        // GridView5行更新前事件
        protected void GridView5_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                // 可以在这里添加更新前的验证逻辑
            }
            catch (Exception ex)
            {
                Response.Write($"<script>alert('更新失败：{ex.Message}');</script>");
                e.Cancel = true;
            }
        }

        // GridView5行删除前事件
        protected void GridView5_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                // 获取要删除的订单ID
                int orderId = Convert.ToInt32(GridView5.DataKeys[e.RowIndex].Value);

                // 这里删除命令已经在SqlDataSource5中配置了级联删除
                // 会先删除Payment表中的记录，再删除OrderProduct表中的记录，最后删除Order表中的记录
            }
            catch (Exception ex)
            {
                Response.Write($"<script>alert('删除失败：{ex.Message}');</script>");
                e.Cancel = true;
            }
        }

        // GridView5行删除完成事件
        protected void GridView5_RowDeleted(object sender, GridViewDeletedEventArgs e)
        {
            if (e.Exception == null)
            {
                Response.Write("<script>alert('订单及相关支付信息删除成功!');</script>");
                // 清空支付信息显示
                SqlDataSource6.SelectParameters["OrderId"].DefaultValue = "-1";
                FormView1.DataBind();
            }
            else
            {
                Response.Write($"<script>alert('删除失败: {e.Exception.Message}');</script>");
                e.ExceptionHandled = true;
            }
        }

        // 支付搜索按钮点击事件
        protected void btnSearchPayment_Click(object sender, EventArgs e)
        {
            try
            {
                string searchType = ddlPaymentSearchType.SelectedValue;
                string searchContent = txtPaymentSearchContent.Text.Trim();

                // 构建动态查询条件
                string whereClause = "1=1"; // 默认条件

                if (!string.IsNullOrEmpty(searchContent))
                {
                    switch (searchType)
                    {
                        case "PayId":
                            if (int.TryParse(searchContent, out int payId))
                            {
                                whereClause = "[PayId] = " + payId;
                            }
                            else
                            {
                                Response.Write("<script>alert('支付编号必须是数字！');</script>");
                                return;
                            }
                            break;
                        case "OrderId":
                            if (int.TryParse(searchContent, out int orderId))
                            {
                                whereClause = "[OrderId] = " + orderId;
                            }
                            else
                            {
                                Response.Write("<script>alert('订单编号必须是数字！');</script>");
                                return;
                            }
                            break;
                        case "PayMethod":
                            whereClause = "[PayMethod] LIKE '%" + searchContent.Replace("'", "''") + "%'";
                            break;
                        case "PayState":
                            whereClause = "[PayState] LIKE '%" + searchContent.Replace("'", "''") + "%'";
                            break;
                    }
                }

                // 更新SqlDataSource的查询命令
                SqlDataSource7.SelectCommand = "SELECT * FROM [Payment] WHERE " + whereClause + " ORDER BY [PayTime] DESC";

                // 重新绑定数据
                GridView6.DataBind();
            }
            catch (Exception ex)
            {
                Response.Write($"<script>alert('搜索失败：{ex.Message}');</script>");
            }
        }

        // 支付重置按钮点击事件
        protected void btnResetPayment_Click(object sender, EventArgs e)
        {
            try
            {
                // 清空搜索控件
                ddlPaymentSearchType.SelectedIndex = 0;
                txtPaymentSearchContent.Text = "";

                // 恢复原始查询命令
                SqlDataSource7.SelectCommand = "SELECT * FROM [Payment] ORDER BY [PayTime] DESC";

                // 重新绑定数据
                GridView6.DataBind();
            }
            catch (Exception ex)
            {
                Response.Write($"<script>alert('重置失败：{ex.Message}');</script>");
            }
        }

        // 获取支付状态样式的方法
        protected string GetPaymentStatusStyle(string payState)
        {
            switch (payState)
            {
                case "未支付":
                    return "color: #dc3545; font-weight: bold; background-color: #f8d7da; padding: 4px 8px; border-radius: 4px; border: 1px solid #f5c6cb;";
                case "支付成功":
                    return "color: #155724; font-weight: bold; background-color: #d4edda; padding: 4px 8px; border-radius: 4px; border: 1px solid #c3e6cb;";
                case "支付失败":
                    return "color: #721c24; font-weight: bold; background-color: #f8d7da; padding: 4px 8px; border-radius: 4px; border: 1px solid #f5c6cb;";
                case "已退款":
                    return "color: #856404; font-weight: bold; background-color: #fff3cd; padding: 4px 8px; border-radius: 4px; border: 1px solid #ffeaa7;";
                default:
                    return "color: #6c757d; font-weight: bold; background-color: #e2e3e5; padding: 4px 8px; border-radius: 4px; border: 1px solid #d6d8db;";
            }
        }

        // 统计信息相关事件处理
        protected void btnRefreshStats_Click(object sender, EventArgs e)
        {
            LoadStatistics();
            Response.Write("<script>alert('统计数据已刷新！');</script>");
        }

        // 加载统计数据
        private void LoadStatistics()
        {
            try
            {
                // 模拟网站访问次数（实际项目中可以从Application或数据库获取）
                if (Application["VisitCount"] == null)
                {
                    Application["VisitCount"] = 1;
                }
                else
                {
                    Application["VisitCount"] = (int)Application["VisitCount"] + 1;
                }
                lblVisitCount.Text = Application["VisitCount"].ToString();

                // 获取在售农产品数量
                SqlDataSourceStats.SelectCommand = "SELECT COUNT(*) FROM Product WHERE Inventory > 0";
                var productCount = GetScalarValue(SqlDataSourceStats.SelectCommand);
                lblProductCount.Text = productCount.ToString();

                // 获取注册用户数量
                SqlDataSourceStats.SelectCommand = "SELECT COUNT(*) FROM Users";
                var userCount = GetScalarValue(SqlDataSourceStats.SelectCommand);
                lblUserCount.Text = userCount.ToString();

                // 获取成功交易数量
                SqlDataSourceStats.SelectCommand = "SELECT COUNT(*) FROM [Order] WHERE OrderState = '已完成'";
                var successOrderCount = GetScalarValue(SqlDataSourceStats.SelectCommand);
                lblSuccessOrderCount.Text = successOrderCount.ToString();

                // 获取总销售金额
                SqlDataSourceStats.SelectCommand = "SELECT ISNULL(SUM(TotalAmout), 0) FROM [Order] WHERE OrderState = '已完成'";
                var totalSales = GetScalarValue(SqlDataSourceStats.SelectCommand);
                lblTotalSales.Text = "¥" + Convert.ToDecimal(totalSales).ToString("F2");

                // 获取待处理订单数量
                SqlDataSourceStats.SelectCommand = "SELECT COUNT(*) FROM [Order] WHERE OrderState IN ('待支付', '已支付', '已发货')";
                var pendingOrders = GetScalarValue(SqlDataSourceStats.SelectCommand);
                lblPendingOrders.Text = pendingOrders.ToString();

                // 获取库存不足商品数量（库存小于10的商品）
                SqlDataSourceStats.SelectCommand = "SELECT COUNT(*) FROM Product WHERE Inventory < 10";
                var lowStockProducts = GetScalarValue(SqlDataSourceStats.SelectCommand);
                lblLowStockProducts.Text = lowStockProducts.ToString();

                // 获取商品分类数量
                SqlDataSourceStats.SelectCommand = "SELECT COUNT(*) FROM ProductCategory";
                var totalCategories = GetScalarValue(SqlDataSourceStats.SelectCommand);
                lblTotalCategories.Text = totalCategories.ToString();

                // 更新最后更新时间
                lblLastUpdateTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            }
            catch (Exception ex)
            {
                Response.Write($"<script>alert('加载统计数据失败：{ex.Message}');</script>");
            }
        }

        // 执行SQL查询并返回标量值
        // 参数 sql: SQL查询语句
        // 返回值: 查询结果
        private object GetScalarValue(string sql)
        {
            try
            {
                using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["AgriculturalSalesConnectionString"].ConnectionString))
                {
                    connection.Open();
                    using (var command = new SqlCommand(sql, connection))
                    {
                        var result = command.ExecuteScalar();
                        return result ?? 0;
                    }
                }
            }
            catch
            {
                return 0;
            }
        }

        // 获取图片URL的方法
        // 参数 imageUrl: 图片URL
        // 返回值: 处理后的图片URL
        protected string GetImageUrl(object imageUrl)
        {
            if (imageUrl == null || string.IsNullOrEmpty(imageUrl.ToString()))
            {
                return ResolveUrl("~/Image/default-product.jpg");
            }

            string url = imageUrl.ToString();

            // 如果已经是完整的相对路径，直接解析
            if (url.StartsWith("~/"))
            {
                return ResolveUrl(url);
            }

            // 如果只是文件名，添加路径前缀
            if (!url.Contains("/"))
            {
                return ResolveUrl("~/Image/" + url);
            }

            return ResolveUrl(url);
        }

        // 获取商品图片URL的方法，包含默认图片处理逻辑
        protected string GetProductImageUrl(object imageUrl)
        {
            try
            {
                // 检查图片URL是否为空或null
                if (imageUrl == null || string.IsNullOrEmpty(imageUrl.ToString().Trim()))
                {
                    return "~/Image/default-product.jpg";
                }

                string url = imageUrl.ToString().Trim();

                // 处理数据库中存储的不同路径格式
                if (url.StartsWith("/images/"))
                {
                    // 将 /images/ 转换为 ~/Image/
                    url = url.Replace("/images/", "~/Image/");
                }
                else if (!url.StartsWith("~/") && !url.StartsWith("http"))
                {
                    // 如果是相对路径，添加 ~/Image/ 前缀
                    url = "~/Image/" + url;
                }

                // 检查文件是否存在（可选）
                string physicalPath = Server.MapPath(url);
                if (!System.IO.File.Exists(physicalPath))
                {
                    return "~/Image/default-product.jpg";
                }

                return url;
            }
            catch (Exception)
            {
                // 发生任何异常时返回默认图片
                return "~/Image/default-product.jpg";
            }
        }

    }
}

